<?php
namespace app\repair\controller;
use think\Request;
use app\common\controller\Common;
use think\Exception;
use think\Db;
class Repair extends Common
{
	protected $model = null;
	protected $keyword_search = ['repair_id','repair_sn','username','phone','user_sn','goods_name','imei','sn','repair_money','actual_money'];
	protected $order = 'repair_id desc';

	// private $state = 'all';
	private $needState = null;//维修单需要改变的状态
	private $rowData = null;//修改的维修单
	private $stateData = [];//修改状态，传递的参数
	protected $afterActionList = [
        'addOperLog'  =>  ['only'=>'repair_add,update_repair_state,up_money,repair_edit,main_repair_edit'],
    ];

	// public function ceshi()
	// {
	// 	$start = 289;
	// 	$data = Db::name('rule_gd')->where('arid','>=',$start)->select();
	// 	$arr = [];
	// 	foreach($data as $k => $v){
	// 		if($v['pid'] >= $start && !in_array($v['pid'], $arr)){
	// 			$arr[] = $v['pid'];
	// 		}
	// 	}
	// 	Db::startTrans();
	// 	$pid = [];
	// 	foreach($data as $k => $v){
	// 		$arid = $v['arid'];
	// 		unset($v['arid']);
	// 		$id = Db::name('rule')->insertGetId($v);
	// 		if(in_array($arid, $arr)){
	// 			$pid[] = $id;
	// 		}
	// 	}
	// 	foreach($arr as $k => $v){
	// 		Db::name('rule')->where('pid',$v)->update(['pid'=>$pid[$k]]);
	// 	}
	// 	Db::commit();
	// 	print_r($pid);
	// }

	public function _initialize()
	{
		parent::_initialize();
        $this->model = model('Repair');
	}

	/**
	 * 营业员
	 * 获取所有维修单
	 * @return [type] [description]
	 */
	public function sale_repair()
	{
		if(Request()->isGet()){
			return $this->fetch();
		}
	}
	/**
	 * 营业员/维修员/总部
	 * 获取各种状态下的维修单
	 * @return [type] [description]
	 */
	public function index()
	{
		if(Request()->isGet()){
			return $this->fetch();
		}
	}
	/**
	 * 维修员
	 * 获取所有维修单
	 * @return [type] [description]
	 */
	public function art_repair()
	{
		if(Request()->isGet()){
			return $this->fetch();
		}
	}
	/**
	 * 获取维修单数据列表
	 */
	public function get_repair()
	{
		if(Request()->isAjax()){
			$data = input('get.');
			$data = Request()->param('');
			$result = $this->getList($data);
			return $result;
		}
	}
	/**
	 * 维修列表统计
	 */
	public function count_repair()
	{
		if(Request()->isGet()){
			$data = input('get.');
			if(Request()->isAjax()){
				$search_arr = isset($data['keyword']) ? $data['keyword'] : '';
				$search = $this->keyword_search($search_arr);
				$order = $this->order;
				$where = $this->handleList($data);

				$count = $this->model->listCount($where, $order, $search);
				$money = $this->model->countRepairMoney($where, $order, $search);
				$this->success(['count'=>$count,'money'=>$money]);
			}
		}
	}
	/**
	 * 新增维修单
	 */
	public function repair_add()
	{
		if(Request()->isGet()){
        	$this->assign('shop_name',$this->model->getShopname(session('admin.shop_id')));
			$this->assign('repair_sn',self::setRepairSn());
			$this->assign('cate',model('Fault')->where('type',config('status.zero_num'))->where('fid',config('status.zero_num'))->select());
			$this->assign('brand',model('Fault')->where('type',config('status.three_num'))->select());
			$this->assign('marker',model('Fault')->where('type',config('status.four_num'))->select());
			return $this->fetch('');
		}
		if(Request()->isPost()){
			$repair = $data = input('post.');
			try{
				Db::startTrans();
				unset($repair['goods']);
				$this->log_ty = $repair['state'];
				/*@添加客户*/
				if($repair['user_sn'] == ''){/*不存在客户*/
					$user = model('user/User');
					$user_result = $user->addUser($repair);
					$repair['user_sn'] = $user->user_sn;
					if($user_result === false){
						Db::rollback();
						$this->error($user->getError());
					}
				}
				/*@添加维修单*/
				$repair['admin_id'] = session('admin.admin_id');
				$repair['shop_id'] = session('admin.shop_id');
				$repair['category_name'] = explode('@@', $repair['category_name'])[0];
				$repair['brand_name'] = explode('@@', $repair['brand_name'])[0];
				$repair['marker'] = explode('@@', $repair['marker'])[0];
				if(isset($repair['repair_id'])){
					unset($repair['repair_id']);
				}
				$ratio = model('RepairRatio')->where('shop_id',session('admin.shop_id'))->find();
				$repair['sale_ratio'] = $ratio['sale_ratio'];
				$repair['sale_t_money'] = $this->repairRatio($repair['people_money'], $repair['sale_ratio']);
				$repair['repair_ratio'] = $ratio['repair_ratio'];
				$repair['repair_t_money'] = $this->repairRatio($repair['people_money'], $repair['repair_ratio']);
				$repair['pay_state'] = $repair['stay_money'] == 0 ? 1 : 0;
				$re_result = $this->model->validate('Repair.add')->allowField(true)->save($repair);
				if($re_result === false){
					Db::rollback();
					$this->error($this->model->getError());
				}
				$this->log_id = $this->model->repair_id;
				/*@添加支付记录*/
				$payLog = model('log/PayLog');
				$payLog->repair_id = $this->model->repair_id;
				$payLog->pay_type = $repair['pay_type'];
				$payLog->actual_money = $repair['actual_money'];
				$payLog->nkname = session('admin.nkname');
				$payLog->save();
				/*@添加维修记录*/
				$repairLog = model('log/RepairLog');
				$a = $repairLog->addLog($this->model->repair_id, $this->getRecord($repair['state']));
				/*@维修配件及库存处理*/
				$RepairGoods = model('RepairGoods');
				/*@添加维修配件-作为记录*/
				$goods_result = $RepairGoods->addRepairGoods($data['goods'], $this->model->repair_id, $this->model->repair_sn);
				if($goods_result === false){
					Db::rollback();
					$this->error($RepairGoods->getError());
				}
				if($repair['state'] == 3){/*确认维修*/
					/*@维修配件及库存处理*/
					$RepairGoods->addTrueRepairGoods($this->model->repair_id);
					// echo Db::getlastsql();exit;
				}
				Db::commit();
				$this->success('所有维修单','/repair/repair/sale_repair');
			}catch(Exception $e){
				Db::rollback();
				$this->error(config('status.ERROR_FIVE').$e->getMessage());
			}
		}
	}
	/**
	* 复制开单 页面
	*/
	public function repair_copy($ids = null)
	{
		$row = $this->model->get($ids);
		if(Request()->isGet()){
			$this->assign('row',$row);
        	$this->assign('shop_name',$this->model->getShopname(session('admin.shop_id')));
			$this->assign('repair_sn',self::setRepairSn());
			$this->assign('cate',model('Fault')->where('type',config('status.zero_num'))->where('fid',config('status.zero_num'))->select());
			$this->assign('brand',model('Fault')->where('type',config('status.three_num'))->select());
			$this->assign('marker',model('Fault')->where('type',config('status.four_num'))->select());
			return $this->fetch('');
		}
	}
	/**
	 * 维修单详情
	 * @param intger $ids 维修单id
	 */
	public function repair_details($ids = null)
	{
		$row = $this->model->get($ids);
		if(Request()->isGet()){
			$this->assign('row',$row);
			return $this->fetch('');
		}
	}
	/**
	 * 维修状态修改
	 * 10 维修取消 未确定->不返库
	 * renew 维修恢复 取消未减库存->不减库存
	 */
	public function update_repair_state($ty = null)
	{
		if(Request()->isAjax()){
			$this->handelState();
			try{
				$this->model->startTrans();
				/*@短信操作
				* 2客户送机+6维修成功	
				*/
				if(in_array($this->needState,[2,6])){
					$this->msg_log_oper();
				}
				/*@3确认维修信息*/
				if($this->needState == 3){
					$this->query_repair();
				}
				/*@4接受维修订单*/
				if($this->needState == 4){
					$this->accept_repair_oper();
				}
				/*@9维修失败*/
				if($this->needState == 9){
					$this->fail_repair_oper();
				}
				/*@10维修取消*/
				if($this->needState == 10){
					$this->cancel_repair_oper();
				}
				/*@状态修改及记录添加*/
				$this->up_state_log();

				$this->model->commit();
				$this->success(config('status.SUCCESS_ONE'));
			}catch(Exception $e){
				$this->model->rollback();
				$this->error(config('status.ERROR_FIVE'). $e->getMessage());
			}
		}
		if(Request()->isGet()){
			$hm = $this->update_repair_hm($ty);
			return $this->fetch($hm);
		}
	}
	/**
	 * 维修状态修改页面
	 */
	private function update_repair_hm($ty)
	{
		/*@客户送机短信*/
		if($ty == 2){
			$message = $this->model->getMessage(1);
			$this->assign('message',$message);
			return 'send_mach';
		}
		/*@维修取消*/
		if($ty == 10) return 'repair_cancel';
		/*@维修失败*/
		if($ty == 9) return 'repair_fail';
		/*@维修完成*/
		if($ty == 6){
			$message = $this->model->getMessage(4);
			$this->assign('message',$message);
			return 'repair_finish';
		} 
	}
	/**
	* 营业员
	* 编辑维修总金额
	*/
	public function up_money()
	{
		if(Request()->isAjax()){
			$data = Request()->param('');
			try{
				if($data['stay_money'] == 0){
					$data['pay_state'] = 1;
				}
				$this->log_id = $data['repair_id'];
				$this->model->allowField(true)->isUpdate(true)->save($data);
				$this->success(config('status.SUCCESS_ONE'));
			}catch(Exception $e){
				$this->error(config('status.ERROR_FIVE'));
			}
		}
	}
	/**
	 * 营业员
	 * 编辑维修单
	 */
	public function repair_edit($ids = null)
	{
		$row = $this->model->get($ids);
		if(Request()->isGet()){
			$this->assign('row',$row);
			return $this->fetch('');
		}
		if(Request()->isAjax()){
			$this->handelState();
			try{
				Db::startTrans();
				/*@修改维修信息*/
				$this->rowData->allowField(true)->save($this->stateData);
				/*@记录*/
				$repairLog = model('log/RepairLog');
				$repairLog->addLog($this->stateData['repair_id'], $this->getRecord($this->needState));
				$RepairGoods = model('RepairGoods');
				/*@库存处理*/
				$RepairGoods->handleGoodsNumber($this->stateData['goods'], $this->stateData['del'], $this->stateData['repair_id']);
				/*@删除维修配件*/
				$RepairGoods->delRepairGoods($this->stateData['repair_id'],$this->stateData['del']);
				/*@编辑维修配件*/
				$goods_result = $RepairGoods->upRepairGoods($this->stateData['goods'], $this->stateData['repair_id'], $this->stateData['repair_sn']);
				if($goods_result === false){
					Db::rollback();
					$this->error($RepairGoods->getError());
				}

				Db::commit();
				$this->success(config('status.SUCCESS_ONE'));
			}catch(Exception $e){
				Db::rollback();
				$this->error(config('status.ERROR_FIVE').$e->getMessage());
			}
		}
	}
	/**
	 * 维修员
	 * 编辑维修单
	 */
	public function main_repair_edit()
	{
		if(Request()->isAjax()){
			$this->handelState();
			try{
				$this->model->startTrans();
				/*@修改维修信息*/
				$this->rowData->allowField(true)->save($this->stateData);
				/*@记录*/
				$repairLog = model('log/RepairLog');
				$repairLog->addLog($this->stateData['repair_id'], $this->getRecord($this->needState));

				$this->model->commit();
				$this->success(config('status.SUCCESS_ONE'));
			}catch(Exception $e){
				$this->model->rollback();
				$this->error(config('status.ERROR_FIVE').$e->getMessage());
			}
		}
	}

	/************************************ 私有方法 *************************************/
	/**
	 * 维修单列表查询条件处理
	 * @param array $data 查询参数
	 */
	protected function handleList($data)
	{
		$where = '';
		/*@登陆者判断*/
		/*店长*/
		if(session('admin.admin_type') == 1){
			$str = '`shop_id` = ' . session('admin.shop_id');
			$where .= $where == '' ? $str : ' and ' . $str;
		}
		/*营业员*/
		if(session('admin.admin_type') == 2){
			$str = '`admin_id` = ' . session('admin.admin_id');
			$where .= $where == '' ? $str : ' and ' . $str;
		}
		/*@状态*/
		if(isset($data['ty']) && $data['ty']){
			if($data['ty'] == 'all'){/*全部*/
				/*维修员*/
				if(session('admin.admin_type') == 3){
					$str = "(`shop_id` = ". session('admin.shop_id') . " and `state` = 3)";
					$str .= " or ((`state` in (4,6,9) or `cancel` = 1 ) and `technician_id` = " . session('admin.admin_id') . ")";
				}
			}else{/*某个状态*/
				if(session('admin.admin_type') == 3){/*维修员*/
					if($data['ty'] == 3){/*待维修*/
						$str = '`shop_id` = ' . session('admin.shop_id');
						$str .= ' and `state` = 3 and `cancel` = 0';
					}else{
						$str = $data['ty'] == 10 ? '`cancel` = 1' : '`state` = ' . $data['ty'] . ' and `cancel` = 0';
						$str .= ' and technician_id = ' . session('admin.admin_id');
					}
				}else{/*不是维修员*/
					$str = $data['ty'] == 10 ? '`cancel` = 1' : '`state` = ' . $data['ty'] . ' and `cancel` = 0'; 
				}
			}
			$where .= $where == '' ? $str : ' and ' . $str; 
		}
		/*@时间*/
		if(isset($data['start']) && $data['start'] != '' && isset($data['end']) && $data['end'] != ''){
			if(strtotime($data['start']) > strtotime($data['end'])){
				return false;
			}
			$str = '`addtime` >= ' . strtotime($data['start']) . ' and `addtime` < ' . strtotime($data['end']);
			$where .= $where == '' ? $str : ' and ' . $str;
		}else if(isset($data['start']) && $data['start'] != ''){
			$str = '`addtime` >= ' . strtotime($data['start']);
			$where .= $where == '' ? $str : ' and ' . $str;
		}else if(isset($data['end']) && $data['end'] != ''){
			$str = '`addtime` < ' . strtotime($data['end']);
			$where .= $where == '' ? $str : ' and ' . $str;
		}
		return $where;
	}
	/**
	 * 生成维修编号
	 */
	private function setRepairSn()
	{
		return config('parameter.repair_sn_prefix') . time() . session('admin.admin_id');
	}
    /**
     * 维修单状态修改及记录添加
     */
    private function up_state_log()
    {
    	/*记录*/
		$repairLog = model('log/RepairLog');
		$repairLog->addLog($this->stateData['repair_id'], $this->getRecord($this->needState));
    	/*维修单状态修改*/
    	if($this->needState == 10){
    		$this->rowData->cancel = 1;
		}else if($this->needState == 'renew'){
			$this->rowData->cancel = 0;
		}else{
    		$this->rowData->state = $this->needState;
    	}
		$this->rowData->save();
    }
    /**
     * 维修单状态修改前 处理
     */
	private function handelState()
	{
		$this->stateData = Request()->param('');
		if(!isset($this->stateData['ty']) || !in_array($this->stateData['ty'],config('repair.state_arr'))){
				$this->error(config('repair.error_ty'));
		}

		$this->log_ty = $this->needState = $this->stateData['ty'];
		$this->log_id = $this->stateData['repair_id'];
		$this->rowData = $row = $this->model->get($this->stateData['repair_id']);
		if(!$row){
			$this->error(config('status.ERROR_TWO'));
		}
		if($this->ifState($row->state, $this->needState, $row->cancel) ){
			$this->error($this->getRecord($row->state, $row->cancel) . ',' . config('status.ERROR_SEVEN'));
		}
	}
	/**
	 * 维修单状态修改前 判断
	 * @param  intger $state      当前维修单状态
	 * @param  intger $cancel     当前维修单取消状态
	 * @param  intger $need_state 需要改变的状态
	 * @return booleen  错误返回true
	 */
	private function ifState($state, $need_state, $cancel)
	{
		/**取消状态提前判断 */
		if(!in_array($need_state,[7,'renew']) && $cancel == 1) return true;
		/*1 等待配件 待确定*/
		if($need_state == 1 && $state != 0) return true;
		/*2 等待客户送机 待确定+等待配件*/
		if($need_state == 2 && !in_array($state,[0,1])) return true;
		/*3 等待维修 待确定+等待配件+等待客户送机*/
		if($need_state == 3 && !in_array($state,[0,1,2])) return true;
		/*4 维修中*/
		if($need_state == 4 && !in_array($state,[3])) return true;
		/*5 维修外送*/
		if($need_state == 5 && !in_array($state,[5])) return true;
		/*6 待取机 维修中+维修外送*/
		if($need_state == 6 && !in_array($state,[4,5])) return true;
		/*7 退款并取机*/
		if($need_state == 7 && ($state != 9 || $cancel == 0) ) return true;
		/*8 付款并取机*/
		if($need_state == 8 && !in_array($state,[6])) return true;
		/*9 维修失败 维修中+维修外送*/
		if($need_state == 9 && !in_array($state,[4,5])) return true;
		/*10 维修取消 待确定+等待配件+等待客户送机+待维修*/
		if($need_state == 10 && !in_array($state,[0,1,2,3]) && $cancel == 1) return true;
		/*edit 营业员 维修编辑 待维修+维修中+维修外送*/
		if($need_state == 'edit' && !in_array($state,[3,4,5])) return true;
		/*edit 维修员 维修编辑 维修中*/
		if($need_state == 'main_edit' && !in_array($state,[4])) return true;
		/**renew 维修恢复 */
		if($need_state == 'renew' && $cancel == 0) return true;
	}
	/**
     * 维修记录值转换
     * @param  intger $state      当前维修单状态
     * @param  intger $cancel     当前维修单取消状态
     */
    private function getRecord($record, $cancel = 0)
    {
    	if($cancel == 1){
    		return config('repair.ten_msg');
    	}
    	switch($record){
    		case '0': return config('repair.zero_msg');break;
    		case '1': return config('repair.one_msg');break;
    		case '2': return config('repair.two_msg');break;
    		case '3': return config('repair.three_msg');break;
    		case '4': return config('repair.four_msg');break;
    		case '5': return config('repair.five_msg');break;
    		case '6': return config('repair.six_msg');break;
    		case '7': return config('repair.seven_msg');break;
    		case '8': return config('repair.eight_msg');break;
    		case '9': return config('repair.nine_msg');break;
    		case '10': return config('repair.ten_msg');break;
    		case 'edit': return config('repair.edit_msg');break;
			case 'main_edit': return config('repair.main_edit_msg');break;
			case 'renew': return config('repair.renew_msg');break;
    		default: $this->error(config('status.ERROR_SIX'));break;
    	}
    }
	/**
	 * 发送短信
	 */
	private function sendMessge()
	{

	}
	/**
	 * 确认维修信息
	 * 减少配件库存
	 */
	private function query_repair()
	{
		/*@维修配件及库存处理*/
		$repairGoods = model('RepairGoods');
		$repairGoods->addTrueRepairGoods($this->stateData['repair_id']);
	}
	/**
	 * 短信操作
	 */
	private function msg_log_oper()
	{
		$message = explode('@@',$this->stateData['message']);
		$this->stateData['message_id'] = $message[0];
		$this->stateData['type'] = $message[1];
		/*@添加短信记录*/
		$msgLog = model('log/MsgLog');
		$msgLog->addMessageLog($this->stateData);
		/*@发送短信*/
		$this->sendMessge();
	}
	/**
	 * 维修单失败操作
	 */
	private function fail_repair_oper()
	{
		/*@取消备注*/
		$repairLog = model('log/RepairLog');
		$repairLog->addFailRemark($this->stateData['repair_id'], $this->stateData['content']);
		/*@返库*/
		$RepairGoods = model('RepairGoods');
		/*未使用的配件 */
		$rgoods = $RepairGoods->where('repair_id',$this->stateData['repair_id'])->where('type',0)->select();
		foreach($rgoods as $k => $v){
			$RepairGoods->addStockRepair($v, $v['number']);
		}
	}
	/**
	 * 维修单取消操作
	 */
	private function cancel_repair_oper()
	{
		/*@取消备注*/
		$repairLog = model('log/RepairLog');
		$repairLog->addRemark($this->stateData['repair_id'], $this->stateData['content']);
		if($this->rowData == 3){/*以确定，已扣库存*/
			/*@返库*/
			$RepairGoods = model('RepairGoods');
			/*未使用的配件 */
			$rgoods = $RepairGoods->where('repair_id',$this->stateData['repair_id'])->where('type',0)->select();
			foreach($rgoods as $k => $v){
				$RepairGoods->addStockRepair($v, $v['number']);
			}
		}
	}
	/**
	 * 接受维修单操作
	 */
	private function accept_repair_oper()
	{
		/*绑定维修员*/
    	$this->rowData->technician_id = session('admin.admin_id');
		$this->rowData->save();
	}

}